package com.mlink.ai.chat.utils

import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import androidx.annotation.ColorInt

class ColorText(private val originalText: String) {
    private val coloredTextList = mutableListOf<ColoredText>()

    fun with(text: String, @ColorInt color: Int): ColorText {
        coloredTextList.add(ColoredText(text, color))
        return this
    }

    fun build(): SpannableStringBuilder {
        val spannableStringBuilder = SpannableStringBuilder(originalText)
        coloredTextList.forEach { coloredText ->
            val startIndex = originalText.indexOf(coloredText.text)
            if (startIndex < 0) {
                return spannableStringBuilder
            }
            val endIndex = startIndex + coloredText.text.length
            spannableStringBuilder.setSpan(
                ForegroundColorSpan(coloredText.color),
                startIndex,
                endIndex,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }
        return spannableStringBuilder
    }

    data class ColoredText(val text: String, @ColorInt val color: Int)
}
